package com.msb.spring;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/****
 * @Author:刘长柏
 * @Date: 2021-01-29 11:35
 * @Description: 反射demo
 *****/
@Slf4j
public class Test {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        UserController userController = new UserController();
        UserService userService = new UserService();
        System.out.println(userService);
        //获取Class对象
        Class<? extends UserController> clazz = userController.getClass();
        //获取想要注入属性的名称
        Field serviceField = clazz.getDeclaredField("userService");
        //获取属性名称
        String name = serviceField.getName();
        //获取方法名称
        name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
        //获取set方法对象
        Method method = clazz.getDeclaredMethod(name, UserService.class);
        //执行set方法
        method.invoke(userController,userService);

        System.out.println(userController.getUserService());
    }
}
